import genService from "@/api/services/tool/genService";
import { ReloadOutlined, SearchOutlined } from "@ant-design/icons";
import { Button, Input, Modal, Space, Table, message } from "antd";
import type { ColumnsType } from "antd/es/table";
import type React from "react";
import { useEffect, useState } from "react";
import type { TableInfo } from "./entity";

/**
 * 数据库表信息接口
 */
export interface DbTableInfo {
	/** 表名称 */
	tableName: string;
	/** 表描述 */
	tableComment: string;
	/** 创建时间 */
	createTime: string;
	/** 更新时间 */
	updateTime: string;
}

interface DbTableSelectProps {
	/** 是否显示弹窗 */
	visible: boolean;
	/** 关闭弹窗回调 */
	onCancel: () => void;
	/** 确认选择回调 */
	onOk: (selectedTables: DbTableInfo[]) => void;
}

/**
 * 数据库表选择组件
 */
const DbTableSelect: React.FC<DbTableSelectProps> = ({ visible, onCancel, onOk }) => {
	const [loading, setLoading] = useState(false);
	const [data, setData] = useState<TableInfo[]>([]);
	const [total, setTotal] = useState(0);
	const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
	const [queryParams, setQueryParams] = useState({
		tableName: undefined as string | undefined,
		tableComment: undefined as string | undefined,
		page: 1,
		pageSize: 10,
	});
	const [okLoading, setOkLoading] = useState(false);

	// 表格列配置
	const columns: ColumnsType<DbTableInfo> = [
		{
			title: "表名称",
			width: 280,
			dataIndex: "tableName",
			key: "tableName",
		},
		{
			title: "表描述",
			dataIndex: "tableComment",
			key: "tableComment",
		},
		{
			title: "创建时间",
			dataIndex: "createTime",
			key: "createTime",
		},
		{
			title: "更新时间",
			dataIndex: "updateTime",
			key: "updateTime",
		},
	];

	// 获取数据库表列表
	const fetchDbTableList = async () => {
		setLoading(true);
		try {
			const res = await genService.dbList(queryParams);
			setData(res.records);
			setTotal(res.total);
		} catch (error) {
			message.error("获取数据库表列表失败");
			console.error("获取数据库表列表失败:", error);
		} finally {
			setLoading(false);
		}
	};

	// 当弹窗显示时加载数据
	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
		useEffect(() => {
		if (visible) {
			fetchDbTableList();
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [visible, queryParams]);

	// 处理查询
	const handleSearch = () => {
		setQueryParams((prev) => ({
			...prev,
			page: 1,
		}));
	};

	// 处理重置
	const handleReset = () => {
		setQueryParams({
			tableName: undefined,
			tableComment: undefined,
			page: 1,
			pageSize: 10,
		});
	};

	// 处理分页变化
	const handlePageChange = (page: number, pageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page,
			pageSize,
		}));
	};

	// 处理确认选择
	const handleOk = async () => {
		if (okLoading) return; // 防止重复点击
		setOkLoading(true);

		if (selectedRowKeys.length === 0) {
			message.warning("请至少选择一张表");
			setOkLoading(false);
			return;
		}

		const selectedTables = data.filter((item) => selectedRowKeys.includes(item.tableName));
		await onOk(selectedTables as unknown as DbTableInfo[]);
		setOkLoading(false);
	};

	// 弹窗关闭时重置 loading
	useEffect(() => {
		if (!visible) setOkLoading(false);
	}, [visible]);

	return (
		<Modal
			title="选择数据库表"
			open={visible}
			onCancel={onCancel}
			width={1000}
			styles={{ body: { overflow: "hidden" } }}
			footer={[
				<Button key="cancel" onClick={onCancel}>
					取消
				</Button>,
				<Button key="ok" type="primary" loading={okLoading} onClick={handleOk}>
					确定
				</Button>,
			]}
		>
			<div className="mb-4">
				<Space>
					<Input
						placeholder="请输入表名称"
						value={queryParams.tableName}
						onChange={(e) => setQueryParams((prev) => ({ ...prev, tableName: e.target.value }))}
						style={{ width: 200 }}
					/>
					<Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
						查询
					</Button>
					<Button icon={<ReloadOutlined />} onClick={handleReset}>
						重置
					</Button>
				</Space>
			</div>

			<div style={{ height: 430 }}>
				<Table
					rowKey="tableName"
					loading={loading}
					columns={columns as unknown as ColumnsType<TableInfo>}
					dataSource={data}
					pagination={{
						total,
						current: queryParams.page,
						pageSize: queryParams.pageSize,
						onChange: handlePageChange,
					}}
					rowSelection={{
						type: "checkbox",
						selectedRowKeys: selectedRowKeys,
						onChange: (selectedKeys) => {
							setSelectedRowKeys(selectedKeys as string[]);
						},
					}}
					scroll={{ y: 300 }}
				/>
			</div>
		</Modal>
	);
};

export default DbTableSelect;
